// Copyright 2023 Leo <lipf160627@163.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package jwt

import (
	"time"

	errCode "gitee.com/lrobin/dl-lab/err-code"
	"github.com/golang-jwt/jwt/v4"
)

type JWT struct {
	SigningKey []byte
}

func NewJWT(signingKey string) *JWT {
	return &JWT{
		SigningKey: []byte(signingKey),
	}
}

func (j *JWT) CreateClaims(baseClaims BaseClaims, expiresTime int64, issuer string) Claims {
	// registeredClaims := new jwt.RegisteredClaims()
	claims := Claims{
		BaseClaims: baseClaims,
		RegisteredClaims: jwt.RegisteredClaims{
			NotBefore: &jwt.NumericDate{Time: time.Now()},                                               // 签名生效时间
			ExpiresAt: &jwt.NumericDate{Time: time.Now().Add(time.Duration(expiresTime) * time.Second)}, // 过期时间
			Issuer:    issuer,                                                                           // 签名的发行者
		},
	}
	return claims
}

// 创建一个token
func (j *JWT) CreateToken(claims Claims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

// // CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
// func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
// 	v, err, _ := global.GVA_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
// 		return j.CreateToken(claims)
// 	})
// 	return v.(string), err
// }

// 解析 token
func (j *JWT) ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})

	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, errCode.ErrTokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, errCode.ErrTokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, errCode.ErrTokenNotValidYet
			} else {
				return nil, errCode.ErrTokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*Claims); ok && token.Valid {
			return claims, nil
		}
		return nil, errCode.ErrTokenInvalid

	} else {
		return nil, errCode.ErrTokenInvalid
	}

}
